<?php


class user_game_favorites_module extends CI_Module {
	public $mytable = "game_favorite";
    public $primaryKey = "gfav_id";
    public $resCode = "GAME_FAVORITE";
	
    function field() {
		$fieldData = array();
		$fieldData['game_id'] = 0;
		$fieldData['use_id'] = 0;
		$fieldData['gfav_time_create'] = 0;
		return $fieldData;
    }
	
	public function init() {
	}
	
	public function active() {
		
	}
	
	public function deactive() {
		
	}
	
	
	public function admin($config) {
		echo $this->view('admin', $config);
	}
	
	/**
	 * 
	 * @param object $config
	 * 
	 */
	public function run($config) {
		if (!isset($config['view'])) {
			$config['view'] = 'index';
		}
		switch ($config['view']) {
			case 'index' :
				$config['games'] = $this->get_game_by_user(@$this->muser->use_id);
				// prd($config['games']);
			break;
			
			case 'add' :
				if (!$this->muser->checkLogin()) return ;
				$config['fgame'] = $this->get(array(
					'use_id' => $this->muser->use_id,
					'game_id' => $config['game_id'],
				));
				
			break;
		}
		$this->view($config['view'], $config);
	}
	
	
	function add_favoriteAction($param) {
		
		$exit = false;
		if (!isset($param[0]))
			$exit = true;
		else if (!$this->muser->checkLogin()) $exit = true;
		else if (!$this->input->is_ajax_request()) $exit = true;
		
		if ($exit) 
		exit('No direct script access allowed');
		
		$game_id = $param[0]; 
		$this->load->model('mgamefavorite');
		$db_debug = $this->db->db_debug;
		$this->db->db_debug = FALSE; 
		$this->insert(array(
		'game_id' => $game_id,
		'use_id' => $this->muser->use_id,
		'gfav_time_create' => time(),
		));
		$this->db->db_debug = $db_debug; 
	}
	
	function remove_favoriteAction($param) {
		$exit = false;
		if (!isset($param[0]))
			$exit = true;
		else if (!$this->muser->checkLogin()) $exit = true;
		else if (!$this->input->is_ajax_request()) $exit = true;
		
		if ($exit) 
		exit('No direct script access allowed');
		
		$game_id = $param[0]; 
		$this->load->model('mgamefavorite');
		$this->db->where('game_id', $game_id);
		$this->db->where('use_id', $this->muser->use_id);
		$this->db->delete($this->mytable);
	}
	
	//Model 
	function get_game_by_user($user_id = 0) {
		if ($user_id > 0)
		return $this->db
				->from($this->mytable . ' as gf')
				->join('game as g', 'g.game_id = gf.game_id')
				->where ('gf.use_id = ', $user_id)
				->order_by('gfav_id desc')
				->get()->result();
		return null;
	}
}